<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import requestTotal from '/@/api/common/common';
import { downloadFileApi, getSupplierBasicInfoPageApi, uploadFileApi } from '/@/api/centerControl/allInterface';
import { sysDictDataList } from '/@/api/centerControl/pubilc';
import { ElMessage } from 'element-plus';
import { sysFileInfoPreviewBase64, sysFileInfoDelete } from '/@/api/centerControl/pubilc';
const { getDictDropDownData } = requestTotal;

const props = defineProps<{
	isShowUploadDialog: boolean;
	fileInfo: string;
}>();

const emits = defineEmits(['closeUploadDialog']);

const activeName = ref('upload');
const handleClick = () => {};

// 上传
const ruleFormUpload = reactive({
	ProviderId: '',
	SourceId: '',
	Files: [],
});
const fileList: any = ref([]);
const handleChange = (file: any) => {
	fileList.value.push(file);
};
const formRefUpload = ref();
const rulesUpload = reactive({
	SourceId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	// ProviderId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
const submitForm = async () => {
	if (!formRefUpload.value) return;
	await formRefUpload.value.validate((valid: any, fields: any) => {
		if (valid) {
			console.log('submit!');
			let setArr: any = [];
			if (fileList.value.length !== 0) {
				fileList.value.map((i: any) => {
					setArr.push(i.raw);
				});
				console.log(setArr, fileList.value, filesTwo.value);

				uploadFileFun(setArr);
			} else {
				ElMessage({
					type: 'error',
					message: '请选择需要上传的文件',
					duration: 1500,
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};
const filesTwo: any = ref([]);
const uploadFileFun = async (file: any) => {
	let param: any = {};
	param.SourceId = ruleFormUpload.SourceId;
	param.ProviderId = myProviderId.value; //供应商
	param.Files = file;
	let res: any = await uploadFileApi(param);
	console.log(res, file, '上传成功');
	fileList.value = [];
    refFile.value.clearFiles();
	// addUploadFiles(file)
};
// const uniqueFiles = ref()
// const addUploadFiles = (list: any) => {
//     if (filesTwo.value.length !== 0) {
//         filesTwo.value.forEach((i: any) => {
//             list.forEach((item: any) => {
//                 if (i.name == item.name && i.documentTye == ruleFormUpload.SourceId) {
//                     return;
//                 } else {
//                     filesTwo.value.push({
//                         supplier: myProviderId.value,
//                         documentTye: ruleFormUpload.SourceId,
//                         name: item.name,
//                         size: item.size
//                     })
//                 }
//             });
//         });
//     } else {
//         list.forEach((item: any) => {
//             filesTwo.value.push({
//                 supplier: myProviderId.value,
//                 documentTye: ruleFormUpload.SourceId,
//                 name: item.name,
//                 size: item.size
//             })
//         });
//     }

//     const uniqueFilesMap = new Map();
//     filesTwo.value.forEach(file => {
//         const key = JSON.stringify({ name: file.name, supplier: file.supplier, documentTye: file.documentTye });

//         if (!uniqueFilesMap.has(key)) {
//             uniqueFilesMap.set(key, file);
//         }
//     });

//     uniqueFiles.value = Array.from(uniqueFilesMap.values());

//     console.log(uniqueFiles, "文件");

// }

const refFile = ref();
const handleRemove = (file: any) => {
	fileList.value.map((itm: any, inx: number) => {
		if (file.uid === itm.uid) {
			fileList.value.splice(inx, 1);
		}
	});
	refFile.value.handleRemove(file);
};

// 下载逻辑
const queryDownloadData = reactive({
	ProviderId: 0,
	DocumentTypeId: '',
});
const fileData: any = ref([]);
const options1: any = ref([]);
const searchVal = ref();
const searchClick = async () => {
	queryDownloadData.DocumentTypeId = searchVal.value;
	await queryDownloadFils(queryDownloadData);
};
const nodeClick = () => {
	searchVal.value = '';
};
const queryDownloadFils = async (data: object) => {
	const res = await downloadFileApi(data);
	fileData.value = [];
	res.data.rows.forEach((item: any) => {
		item.v_FilePath.forEach((i: any) => {
			i.name = item.documentName;
			fileData.value.push(i);
		});
	});
	console.log(fileData.value, 'fileData');
};

// 关闭
const closeUploadDialog1 = () => {
	searchVal.value = '';
	queryDownloadData.DocumentTypeId = '';
	activeName.value = 'upload';
	formRefUpload.value.resetFields();
	refFile.value.clearFiles();
    fileList.value = [];
	// filesTwo.value = [];
	// uniqueFiles.value = [];
	emits('closeUploadDialog', false);
};

/*** delClick 删除文件事件 */
const delClick = async (val: Number) => {
	console.log(val, 'val');
	let param: any = {};
	param.id = val;
	await sysFileInfoDelete(param);
	await searchClick();
	// if (res.success) {
	//     getPageFile(JSON.parse(props.fileInfo).sourceId);
	// }
};

/*** downClick 下载文件 */
const downClick = async (val: any) => {
	let getFile = getFileFun(val.id);
	// 等待getFileFun完成
	await getFile;
	if (getFile && getFile.then) {
		getFile.then((res) => {
			let base64Data = res;
			let blob = base64ToBlob(base64Data);

			// 创建可下载的链接
			let url = URL.createObjectURL(blob);
			let link = document.createElement('a');
			link.href = url;
			link.download = val.fileOriginName; // 指定下载的文件名

			// 将链接添加到DOM中
			document.body.appendChild(link);

			// 触发点击事件开始下载
			link.click();

			// 释放临时URL
			URL.revokeObjectURL(url);
		});
	}
};
/*** getFileFun 获取文件数据 */
const getFileFun = async (val: Number) => {
	let param: any = {};
	param.id = val;
	let res: any = await sysFileInfoPreviewBase64(param);
	console.log(res, 'res');
	if (res.success) {
		return res.data;
	}
};
// 将Base64编码数据转换为Blob对象的辅助函数
const base64ToBlob = (base64Data: any) => {
	var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
	var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], { type: mimeString });
};

const myProviderId = ref();
watch(
	() => props.isShowUploadDialog,
	(val) => {
		if (val) {
			const obj = JSON.parse(props.fileInfo);
			console.log(obj);
			myProviderId.value = obj.n_Id;
			queryDownloadData.ProviderId = obj.n_Id;
			queryDownloadFils(queryDownloadData);
		}
	},
	{ immediate: true }
);

const options3: any = ref([]);
const options2: any = ref([]);
onMounted(async () => {
	// 上传
	const res3 = await getSupplierBasicInfoPageApi();
	console.log(res3);
	res3.data.rows.forEach((element: any) => {
		options3.value.push({
			label: element.value,
			value: element.n_Id,
		});
	});

	const res2 = await sysDictDataList({ TypeCode: 'ProviderDocType' });
	console.log(res2);
	res2.data.forEach((element: any) => {
		options2.value.push({
			label: element.value,
			value: element.id,
		});
	});

	// 下载
	const res = await getDictDropDownData({ Code: 'ProviderDocType' });
	res.data.forEach((element: any) => {
		options1.value.push({
			value: element.id,
			label: element.value,
		});
	});
});

/*** viewClick 文件预览 */
// const baseUrl = import.meta.env.VITE_APP_API_EQU_URL;
const baseUrl = import.meta.env.VITE_API_URL;
const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;
const viewClick = async (val: any) => {
	let viewUrl = baseUrl + 'api/' + val.path;
	window.open(viewUrl);
};
</script>
<template>
	<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="props.isShowUploadDialog" title="附件管理" width="50%" @close="closeUploadDialog1">
		<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
			<el-tab-pane label="文件上传" name="upload">
				<el-form :model="ruleFormUpload" :rules="rulesUpload" ref="formRefUpload">
					<el-divider content-position="left"> 基本信息 </el-divider>
					<el-row :gutter="20">
						<!-- <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
                            <el-form-item prop="ProviderId" label="供应商">
                                <el-select v-model="ruleFormUpload.ProviderId" class="m-2" placeholder="请选择供应商"
                                    style="width: 180px">
                                    <el-option v-for="item in options3" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col> -->
						<el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
							<el-form-item prop="SourceId" label="文档类型">
								<el-select v-model="ruleFormUpload.SourceId" class="m-2" placeholder="请选择文档类型" style="width: 180px">
									<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
								</el-select> </el-form-item
						></el-col>
						<el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb20"> <el-button style="width: 100px" type="primary" @click="submitForm">上传附件</el-button></el-col>
						<el-divider content-position="left"> 附件 </el-divider>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item>
								<el-upload action="#" ref="refFile" list-type="picture-card" :auto-upload="false" :on-change="handleChange" multiple class="upload-s">
									<el-icon>
										<Plus />
									</el-icon>
									<template #file="{ file }">
										<template v-if="file.name.split('.')[1] === 'jpeg' || file.name.split('.')[1] === 'jpg' || file.name.split('.')[1] === 'png'">
											<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
										</template>

										<template v-else>
											<span class="file-s">{{ file.name }}</span>
										</template>

										<span class="el-upload-list__item-actions set-bg" style="background-color: rgba(0, 0, 0, 0.5) !important">
											<span class="el-upload-list__item-delete" @click="handleRemove(file)" style="background: rgba(0, 0, 0, 0) !important">
												<el-icon>
													<Delete />
												</el-icon>
											</span>
										</span>
									</template>
								</el-upload>
							</el-form-item>
						</el-col>

						<!-- <el-divider content-position="left"> 已上传附件查看 </el-divider>
                        <el-table :data="uniqueFiles" border>
                            <el-table-column prop="supplier" label="供应商" align="center">
                                <template #default="scope">
                                    {{ options3.find((item) => item.value === scope.row.supplier).label }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="documentTye" label="文档类型" align="center">
                                <template #default="scope">
                                    {{ options2.find((item) => item.value === scope.row.documentTye).label }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="文件名称" align="center" />
                            <el-table-column prop="size" label="文件大小(kb)" align="center" />
                        </el-table> -->
					</el-row>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="文件下载" name="download">
				<el-form class="box-f" ref="queryForm" :inline="true">
					<el-form-item label="类型">
						<el-select v-model="searchVal" placeholder="请选择类型" clearable style="width: 100%">
							<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>

					<el-form-item>
						<el-button @click="searchClick" icon="ele-Search" type="primary">查询</el-button>
						<el-button @click="nodeClick" icon="ele-Refresh"> 重置</el-button>
					</el-form-item>
				</el-form>
				<el-table class="heightcss" :data="fileData" style="width: 100%" element-loading-background="rgba(0, 0, 0, 0.5)" border>
					<el-table-column type="index" label="序号" min-width="60" align="center" />
					<el-table-column prop="name" label="类型" min-width="120" align="center" :show-overflow-tooltip="true" />
					<!-- <el-table-column prop="path" label="文件路径" min-width="140" align="center"
                        :show-overflow-tooltip="true" /> -->
					<el-table-column prop="createdUserName" label="上传人" min-width="100" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="createdTime" label="上传时间" min-width="120" align="center" :show-overflow-tooltip="true" />
					<el-table-column fixed="right" prop="operation" label="操作" show-overflow-tooltip min-width="140" align="center">
						<template #default="scope">
							<el-button @click="viewClick(scope.row)" class="icon-e" text type="success">预览</el-button>
							<el-button @click="downClick(scope.row)" class="icon-e" text type="warning">下载</el-button>
							<el-button @click="delClick(scope.row.id)" class="icon-e" text type="danger">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-tab-pane>
		</el-tabs>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeUploadDialog1">关闭</el-button>
			</div>
		</template>
	</el-dialog>
</template>
<style scoped></style>
